/**
 * @file test_real_world.cpp
 * @brief 真实世界Verilog文件测试
 * 使用a9soc项目中的实际Verilog文件测试moparse工具的实际性能和兼容性
 */

#include "../moparse.h"
#include <iostream>
#include <fstream>
#include <cassert>
#include <functional>
#include <cstdio>
#include <chrono>
#include <vector>
#include <string>

class RealWorldTestRunner {
public:
    RealWorldTestRunner() : tests_passed_(0), tests_failed_(0) {}
    
    void run_test(const std::string& test_name, std::function<bool()> test_func) {
        std::cout << "运行真实世界测试: " << test_name << " ... ";
        auto start = std::chrono::high_resolution_clock::now();
        
        try {
            if (test_func()) {
                auto end = std::chrono::high_resolution_clock::now();
                auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
                std::cout << "通过 (" << duration.count() << "ms)" << std::endl;
                tests_passed_++;
            } else {
                auto end = std::chrono::high_resolution_clock::now();
                auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
                std::cout << "失败 (" << duration.count() << "ms)" << std::endl;
                tests_failed_++;
            }
        } catch (const std::exception& e) {
            std::cout << "异常: " << e.what() << std::endl;
            tests_failed_++;
        }
    }
    
    void print_summary() {
        std::cout << "\n真实世界测试总结:" << std::endl;
        std::cout << "通过: " << tests_passed_ << std::endl;
        std::cout << "失败: " << tests_failed_ << std::endl;
        std::cout << "总计: " << (tests_passed_ + tests_failed_) << std::endl;
        
        if (tests_failed_ == 0) {
            std::cout << "\n🎉 所有真实世界测试通过！moparse工具已准备好处理实际项目。" << std::endl;
        } else {
            std::cout << "\n⚠️  有 " << tests_failed_ << " 个测试失败，可能需要进一步优化。" << std::endl;
        }
    }
    
    int get_failed_count() const { return tests_failed_; }

private:
    int tests_passed_;
    int tests_failed_;
};

// 真实世界的Verilog文件路径
std::vector<std::string> get_real_verilog_files() {
    return {
        // A9 处理器相关文件
        "../../a9soc/design/a9/src/1024x21_L.v",
        "../../a9soc/design/a9/src/1024x32by.v", 
        "../../a9soc/design/a9/src/1024x32w.v",
        "../../a9soc/design/a9/src/4096x256.v",
        "../../a9soc/design/a9/src/512K_DATARAM.v",
        "../../a9soc/design/a9/src/512K_TAGRAM.v",
        "../../a9soc/design/a9/src/A9_L2_DAPLite_top.v",
        
        // Timers 模块文件
        "../../a9soc/design/Timers/src/Timers.v",
        "../../a9soc/design/Timers/src/TimersFrc.v",
        "../../a9soc/design/Timers/src/TimersPackage.v",
        "../../a9soc/design/Timers/src/TimersRevAnd.v",
        
        // 生成的文件
        "../../a9soc/bin/gen/chip.v",
        "../../a9soc/bin/gen/chip_fpga.v",
        "../../a9soc/bin/gen/iopad.v",
        "../../a9soc/bin/gen/iopad_fpga.v",
        "../../a9soc/bin/gen/pmu_reg.v",
        "../../a9soc/bin/gen/sysc_reg.v",
        "../../a9soc/bin/sysc_stub.v"
    };
}

// 创建真实世界测试的文件列表
void create_real_world_filelist() {
    std::ofstream a9_list("a9_design.list");
    a9_list << "# A9 SoC 设计文件列表\n";
    a9_list << "# A9 处理器核心文件\n";
    a9_list << "../../a9soc/design/a9/src/1024x21_L.v\n";
    a9_list << "../../a9soc/design/a9/src/1024x32by.v\n";
    a9_list << "../../a9soc/design/a9/src/1024x32w.v\n";
    a9_list << "../../a9soc/design/a9/src/4096x256.v\n";
    a9_list << "../../a9soc/design/a9/src/512K_DATARAM.v\n";
    a9_list << "../../a9soc/design/a9/src/512K_TAGRAM.v\n";
    a9_list << "../../a9soc/design/a9/src/A9_L2_DAPLite_top.v\n";
    a9_list.close();
    
    std::ofstream timers_list("timers_design.list");
    timers_list << "# Timers 模块文件列表\n";
    timers_list << "../../a9soc/design/Timers/src/Timers.v\n";
    timers_list << "../../a9soc/design/Timers/src/TimersFrc.v\n";
    timers_list << "../../a9soc/design/Timers/src/TimersPackage.v\n";
    timers_list << "../../a9soc/design/Timers/src/TimersRevAnd.v\n";
    timers_list.close();
    
    std::ofstream generated_list("generated_design.list");
    generated_list << "# 生成的设计文件列表\n";
    generated_list << "../../a9soc/bin/gen/chip.v\n";
    generated_list << "../../a9soc/bin/gen/chip_fpga.v\n";
    generated_list << "../../a9soc/bin/gen/iopad.v\n";
    generated_list << "../../a9soc/bin/gen/iopad_fpga.v\n";
    generated_list << "../../a9soc/bin/gen/pmu_reg.v\n";
    generated_list << "../../a9soc/bin/gen/sysc_reg.v\n";
    generated_list << "../../a9soc/bin/sysc_stub.v\n";
    generated_list.close();
    
    // 创建主文件列表
    std::ofstream main_list("a9soc_complete.list");
    main_list << "# A9 SoC 完整设计文件列表\n";
    main_list << "# 使用嵌套文件列表组织\n";
    main_list << "-f a9_design.list\n";
    main_list << "-f timers_design.list\n";
    main_list << "-f generated_design.list\n";
    main_list.close();
}

// 清理真实世界测试文件
void cleanup_real_world_files() {
    std::vector<std::string> files = {
        "a9_design.list", "timers_design.list", "generated_design.list", "a9soc_complete.list",
        "a9_output.modb", "timers_output.modb", "generated_output.modb", "complete_output.modb",
        "performance_test.modb", "stress_test.modb", "reverse_gen_test.v"
    };
    
    for (const auto& file : files) {
        std::remove(file.c_str());
    }
}

// 测试单个真实Verilog文件解析
bool test_single_real_file() {
    VerilogParser parser;
    
    // 测试一个已知存在的文件
    std::string test_file = "../../a9soc/design/Timers/src/Timers.v";
    
    std::ifstream file_check(test_file);
    if (!file_check.is_open()) {
        std::cout << "警告: 测试文件不存在 " << test_file;
        return true; // 文件不存在不算失败
    }
    file_check.close();
    
    if (!parser.parseVerilogFile(test_file)) {
        return false;
    }
    
    const auto& db = parser.getDatabase();
    
    // 验证解析结果
    if (db.modules_size() == 0) {
        return false;
    }
    
    std::cout << "\n    解析出 " << db.modules_size() << " 个模块 ";
    return true;
}

// 测试A9设计文件解析
bool test_a9_design_files() {
    VerilogParser parser;
    
    if (!parser.parseVerilogFileList("a9_design.list")) {
        return false;
    }
    
    const auto& db = parser.getDatabase();
    std::cout << "\n    A9设计文件解析出 " << db.modules_size() << " 个模块 ";
    
    // 保存结果
    return parser.saveToModb("a9_output.modb");
}

// 测试Timers模块文件解析
bool test_timers_design_files() {
    VerilogParser parser;
    
    if (!parser.parseVerilogFileList("timers_design.list")) {
        return false;
    }
    
    const auto& db = parser.getDatabase();
    std::cout << "\n    Timers文件解析出 " << db.modules_size() << " 个模块 ";
    
    return parser.saveToModb("timers_output.modb");
}

// 测试生成的设计文件解析
bool test_generated_design_files() {
    VerilogParser parser;
    
    if (!parser.parseVerilogFileList("generated_design.list")) {
        return false;
    }
    
    const auto& db = parser.getDatabase();
    std::cout << "\n    生成文件解析出 " << db.modules_size() << " 个模块 ";
    
    return parser.saveToModb("generated_output.modb");
}

// 测试完整A9 SoC设计解析
bool test_complete_a9soc_design() {
    VerilogParser parser;
    
    if (!parser.parseVerilogFileList("a9soc_complete.list")) {
        return false;
    }
    
    const auto& db = parser.getDatabase();
    std::cout << "\n    完整A9 SoC设计解析出 " << db.modules_size() << " 个模块 ";
    
    if (db.modules_size() == 0) {
        return false;
    }
    
    return parser.saveToModb("complete_output.modb");
}

// 测试大批量文件处理性能
bool test_batch_processing_performance() {
    VerilogParser parser;
    
    auto start = std::chrono::high_resolution_clock::now();
    
    // 连续处理多个文件列表
    if (!parser.parseVerilogFileList("a9_design.list")) {
        return false;
    }
    
    if (!parser.parseVerilogFileList("timers_design.list")) {
        return false;
    }
    
    if (!parser.parseVerilogFileList("generated_design.list")) {
        return false;
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    
    const auto& db = parser.getDatabase();
    std::cout << "\n    批量处理: " << db.modules_size() << " 个模块，耗时: " << duration.count() << "ms ";
    
    return parser.saveToModb("performance_test.modb");
}

// 测试内存使用和稳定性
bool test_memory_stability() {
    // 创建多个解析器实例测试内存使用
    std::vector<VerilogParser> parsers(5);
    
    for (auto& parser : parsers) {
        if (!parser.parseVerilogFileList("a9_design.list")) {
            return false;
        }
    }
    
    // 检查所有解析器的结果一致性
    int expected_modules = parsers[0].getDatabase().modules_size();
    for (const auto& parser : parsers) {
        if (parser.getDatabase().modules_size() != expected_modules) {
            return false;
        }
    }
    
    std::cout << "\n    内存稳定性测试: 5个解析器实例，每个 " << expected_modules << " 个模块 ";
    return true;
}

// 测试错误恢复能力
bool test_error_recovery_with_real_files() {
    VerilogParser parser;
    
    // 创建包含存在和不存在文件的混合列表
    std::ofstream mixed_list("mixed_real_files.list");
    mixed_list << "../../a9soc/design/Timers/src/Timers.v\n";
    mixed_list << "nonexistent_file.v\n";  // 不存在的文件
    mixed_list << "../../a9soc/bin/gen/chip.v\n";
    mixed_list << "another_nonexistent.v\n";  // 另一个不存在的文件
    mixed_list.close();
    
    // 应该能够处理错误并继续解析存在的文件
    bool result = parser.parseVerilogFileList("mixed_real_files.list");
    
    const auto& db = parser.getDatabase();
    std::cout << "\n    错误恢复测试: 解析出 " << db.modules_size() << " 个模块 ";
    
    std::remove("mixed_real_files.list");
    
    // 至少应该解析出一些模块（从存在的文件）
    return db.modules_size() > 0;
}

// 测试真实文件的反向生成
bool test_real_file_reverse_generation() {
    VerilogParser parser;
    
    // 解析一个真实文件
    if (!parser.parseVerilogFile("../../a9soc/design/Timers/src/Timers.v")) {
        std::cout << "\n    源文件解析失败 ";
        return true; // 文件可能不存在，不算失败
    }
    
    const auto& db = parser.getDatabase();
    if (db.modules_size() == 0) {
        return false;
    }
    
    // 保存到modb
    if (!parser.saveToModb("real_module_test.modb")) {
        return false;
    }
    
    // 获取第一个模块进行反向生成测试
    std::string module_name = db.modules(0).name();
    
    // 测试反向生成
    if (!parser.generateVerilog("real_module_test.modb", module_name, "reverse_gen_test.v", "e")) {
        return false;
    }
    
    // 验证生成的文件
    std::ifstream gen_file("reverse_gen_test.v");
    if (!gen_file.is_open()) {
        return false;
    }
    
    std::string content;
    std::string line;
    while (std::getline(gen_file, line)) {
        content += line + "\n";
    }
    
    std::cout << "\n    反向生成测试: 模块 " << module_name << " ";
    
    std::remove("real_module_test.modb");
    
    return content.find(module_name) != std::string::npos;
}

// 测试复杂模块的详细解析
bool test_complex_module_analysis() {
    VerilogParser parser;
    
    // 解析一个复杂的A9文件
    std::string complex_file = "../../a9soc/design/a9/src/A9_L2_DAPLite_top.v";
    
    std::ifstream file_check(complex_file);
    if (!file_check.is_open()) {
        std::cout << "\n    复杂文件不存在 ";
        return true; // 文件不存在不算失败
    }
    file_check.close();
    
    if (!parser.parseVerilogFile(complex_file)) {
        return false;
    }
    
    const auto& db = parser.getDatabase();
    if (db.modules_size() == 0) {
        return false;
    }
    
    // 分析解析结果
    int total_ports = 0;
    int total_params = 0;
    int total_instances = 0;
    
    for (const auto& module : db.modules()) {
        total_ports += module.ports_size();
        total_params += module.parameters_size();
        total_instances += module.instances_size();
    }
    
    std::cout << "\n    复杂模块分析: " << db.modules_size() << " 模块, " 
              << total_ports << " 端口, " << total_params << " 参数, " 
              << total_instances << " 实例 ";
    
    return true;
}

int main() {
    std::cout << "开始A9 SoC真实世界Verilog测试...\n" << std::endl;
    
    // 创建真实世界测试文件列表
    create_real_world_filelist();
    
    RealWorldTestRunner runner;
    
    // 运行真实世界测试
    runner.run_test("单个真实文件解析", test_single_real_file);
    runner.run_test("A9设计文件解析", test_a9_design_files);
    runner.run_test("Timers模块解析", test_timers_design_files);
    runner.run_test("生成文件解析", test_generated_design_files);
    runner.run_test("完整A9 SoC解析", test_complete_a9soc_design);
    runner.run_test("批量处理性能", test_batch_processing_performance);
    runner.run_test("内存稳定性", test_memory_stability);
    runner.run_test("错误恢复能力", test_error_recovery_with_real_files);
    runner.run_test("真实文件反向生成", test_real_file_reverse_generation);
    runner.run_test("复杂模块分析", test_complex_module_analysis);
    
    // 清理测试文件
    cleanup_real_world_files();
    
    // 输出测试结果
    runner.print_summary();
    
    return runner.get_failed_count() > 0 ? 1 : 0;
}